<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>Javascript中的复制粘贴功能 | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="JavaScript,复制粘贴,">
  

  <meta name="description" content="来源网络  一、基本使用1.1 API 介绍复制、剪切、粘贴事件  copy 发生复制操作时触发; cut 发生剪切操作时触发; paste 发生粘贴操作时触发   每个事件都有一个 before 事件对应：beforecopy、beforecut、beforepaste。这几个 before 一般不怎么用，所以我们把注意力放在另外三个事件就可以了  触发条件  鼠标右键菜单的复制、粘贴、剪切">
<meta name="keywords" content="JavaScript,复制粘贴">
<meta property="og:type" content="article">
<meta property="og:title" content="Javascript中的复制粘贴功能">
<meta property="og:url" content="http://blog.poetries.top/2018/12/23/js-copy/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="来源网络  一、基本使用1.1 API 介绍复制、剪切、粘贴事件  copy 发生复制操作时触发; cut 发生剪切操作时触发; paste 发生粘贴操作时触发   每个事件都有一个 before 事件对应：beforecopy、beforecut、beforepaste。这几个 before 一般不怎么用，所以我们把注意力放在另外三个事件就可以了  触发条件  鼠标右键菜单的复制、粘贴、剪切">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/1480597-2f3188629fa5a86d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2020-08-15T04:25:31.926Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Javascript中的复制粘贴功能">
<meta name="twitter:description" content="来源网络  一、基本使用1.1 API 介绍复制、剪切、粘贴事件  copy 发生复制操作时触发; cut 发生剪切操作时触发; paste 发生粘贴操作时触发   每个事件都有一个 before 事件对应：beforecopy、beforecut、beforepaste。这几个 before 一般不怎么用，所以我们把注意力放在另外三个事件就可以了  触发条件  鼠标右键菜单的复制、粘贴、剪切">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/1480597-2f3188629fa5a86d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、基本使用"><span class="toc-text">一、基本使用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-API-介绍"><span class="toc-text">1.1 API 介绍</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-clipboardData"><span class="toc-text">1.2 clipboardData</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、应用"><span class="toc-text">二、应用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-复制大段文本"><span class="toc-text">2.1 复制大段文本</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-防复制功能"><span class="toc-text">2.2 防复制功能</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-点击复制功能"><span class="toc-text">2.3 点击复制功能</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-4-第三方库clipboard"><span class="toc-text">2.4 第三方库clipboard</span></a></li></ol></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-js-copy" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">Javascript中的复制粘贴功能</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2018.12.23</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 1.5k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 6分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <blockquote>
<p>来源网络</p>
</blockquote>
<h2 id="一、基本使用"><a href="#一、基本使用" class="headerlink" title="一、基本使用"></a>一、基本使用</h2><h3 id="1-1-API-介绍"><a href="#1-1-API-介绍" class="headerlink" title="1.1 API 介绍"></a>1.1 API 介绍</h3><p><strong>复制、剪切、粘贴事件</strong></p>
<ul>
<li><code>copy</code> 发生复制操作时触发;</li>
<li><code>cut</code> 发生剪切操作时触发;</li>
<li><code>paste</code> 发生粘贴操作时触发</li>
</ul>
<blockquote>
<p>每个事件都有一个 <code>before</code> 事件对应：<code>beforecopy</code>、<code>beforecut</code>、<code>beforepaste</code>。这几个 <code>before</code> 一般不怎么用，所以我们把注意力放在另外三个事件就可以了</p>
</blockquote>
<p><strong>触发条件</strong></p>
<ul>
<li>鼠标右键菜单的<code>复制</code>、<code>粘贴</code>、<code>剪切</code></li>
<li>使用了相应的键盘组合键，比如:<code>command+c</code>、<code>command+v</code></li>
</ul>
<p><strong>使用姿势</strong></p>
<blockquote>
<p>以 <code>copy</code> 为例</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="built_in">document</span>.body.oncopy = <span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// 监听全局复制 做点什么</span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">// 还有这种写法：</span></span><br><span class="line"><span class="built_in">document</span>.addEventListener(<span class="string">'copy'</span>, e =&gt; &#123;</span><br><span class="line">  <span class="comment">// 监听全局复制 做点什么</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>上面是在<code>document.body</code>上全局监听的，然而很多人不知道的是，我们还可以为某些 <code>dom</code> 单独添加剪切板事件</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">// html结构</span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"test1"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"test2"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">    <span class="comment">// 写法一样：</span></span></span><br><span class="line"><span class="javascript">    <span class="keyword">let</span> test1 = <span class="built_in">document</span>.querySelector(<span class="string">'#test1'</span>);</span></span><br><span class="line"><span class="javascript">    test1.oncopy = <span class="function"><span class="params">e</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">        <span class="comment">// 监听test1发生的复制事件 做点什么</span></span></span><br><span class="line"><span class="javascript">        <span class="comment">// test1发生的复制事件会触发回调，其他地方不会触发回调</span></span></span><br><span class="line">    &#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>其他事件也是一样的</p>
</blockquote>
<h3 id="1-2-clipboardData"><a href="#1-2-clipboardData" class="headerlink" title="1.2 clipboardData"></a>1.2 clipboardData</h3><p><strong>clipboardData 对象:用于访问以及修改剪贴板中的数据</strong></p>
<blockquote>
<p>不同浏览器，所属的对象不同：在 <code>IE</code> 中这个对象是<code>window</code>对象的属性，在<code>Chrome</code>、<code>Safari</code>和<code>Firefox</code>中，这个对象是相应的<code>event</code>对象的属性。所以我们在使用的时候，需要做一下如下兼容</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="built_in">document</span>.body.oncopy = <span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">let</span> clipboardData = e.clipboardData || <span class="built_in">window</span>.clipboardData;</span><br><span class="line">  <span class="comment">// 获取clipboardData对象 + do something</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p><strong>对象方法</strong></p>
<blockquote>
<p>对象有三个方法: <code>getData()</code>、<code>setData()</code>、<code>clearData()</code></p>
</blockquote>
<p><strong>getData() 访问剪切板中的数据</strong></p>
<blockquote>
<p><code>getData()</code>接受一个<code>text</code>参数，即要取得的数据的格式</p>
</blockquote>
<p><strong>在复制、剪切、粘贴触发的事件的数据</strong></p>
<blockquote>
<p>实际上在 <code>chorme</code> 上测试只有<code>paste</code>粘贴的时候才能用<code>getData()</code>访问到数据，用法如下</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 要粘贴的数据：</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">document</span>.body.onpaste = <span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">let</span> clipboardData = e.clipboardData || <span class="built_in">window</span>.clipboardData; <span class="comment">// 兼容处理</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'要粘贴的数据'</span>, clipboardData.getData(<span class="string">'text'</span>));</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p><strong>被复制/剪切的数据</strong>：</p>
<blockquote>
<p>在复制和剪切中的数据，需要通过<code>window.getSelection(0).toString()</code>来访问:</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="built_in">document</span>.body.oncopy = <span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'被复制的数据:'</span>, <span class="built_in">window</span>.getSelection(<span class="number">0</span>).toString());</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p><strong>setData(): 修改剪切板中的数据</strong></p>
<blockquote>
<p>第一个参数也是<code>text</code>，第二个参数是要放在剪切板中的文本</p>
</blockquote>
<p><strong>clearData()</strong></p>
<h2 id="二、应用"><a href="#二、应用" class="headerlink" title="二、应用"></a>二、应用</h2><h3 id="2-1-复制大段文本"><a href="#2-1-复制大段文本" class="headerlink" title="2.1 复制大段文本"></a>2.1 复制大段文本</h3><p><strong>实现类知乎/掘金复制大段文本添加版权信息</strong></p>
<blockquote>
<p>实现很简单：取消默认复制之后，主要是在被复制的内容后面添加信息，然后根据 <code>clipboardData</code> 的 <code>setData()</code>方法将信息写入剪贴板</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 掘金这里不是全局监听，应该只是监听文章的dom范围内。</span></span><br><span class="line"><span class="built_in">document</span>.body.oncopy = <span class="function"><span class="params">event</span> =&gt;</span> &#123;</span><br><span class="line">  event.preventDefault(); <span class="comment">// 取消默认的复制事件</span></span><br><span class="line">  <span class="keyword">let</span> textFont,</span><br><span class="line">    copyFont = <span class="built_in">window</span>.getSelection(<span class="number">0</span>).toString(); <span class="comment">// 被复制的文字 等下插入</span></span><br><span class="line">  <span class="comment">// 防知乎掘金 复制一两个字则不添加版权信息 超过一定长度的文字 就添加版权信息</span></span><br><span class="line">  <span class="keyword">if</span> (copyFont.length &gt; <span class="number">10</span>) &#123;</span><br><span class="line">    textFont =</span><br><span class="line">      copyFont +</span><br><span class="line">      <span class="string">'\n'</span> +</span><br><span class="line">      <span class="string">'作者：OBKoro1\n'</span> +</span><br><span class="line">      <span class="string">'链接：https://juejin.im/user/58714f0e325b123db4a2eb95372/posts\n'</span> +</span><br><span class="line">      <span class="string">'来源：掘金\n'</span> +</span><br><span class="line">      <span class="string">'著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。'</span>;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    textFont = copyFont; <span class="comment">// 没超过十个字 则采用被复制的内容。</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (event.clipboardData) &#123;</span><br><span class="line">    <span class="keyword">return</span> event.clipboardData.setData(<span class="string">'text'</span>, textFont); <span class="comment">// 将信息写入粘贴板</span></span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// 兼容IE</span></span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">window</span>.clipboardData.setData(<span class="string">'text'</span>, textFont);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>然后 <code>command+c</code>、<code>command+v</code>，输出:</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">你复制的内容</span><br><span class="line">作者：OBKoro1</span><br><span class="line">链接：https://juejin.im/user/58714f0eb123db4a2eb95372/posts</span><br><span class="line">来源：掘金</span><br><span class="line">著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。</span><br></pre></td></tr></table></figure>
<h3 id="2-2-防复制功能"><a href="#2-2-防复制功能" class="headerlink" title="2.2 防复制功能"></a>2.2 防复制功能</h3><ul>
<li>禁止复制+剪切</li>
<li>禁止右键，右键某些选项:全选，复制，粘贴等。</li>
<li>禁用文字选择，能选择却不能复制，体验很差。</li>
<li><code>user-select</code> 用 <code>css</code> 禁止选择文本</li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 禁止右键菜单</span></span><br><span class="line"><span class="built_in">document</span>.body.oncontextmenu = <span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(e, <span class="string">'右键'</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="comment">// e.preventDefault();</span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">// 禁止文字选择。</span></span><br><span class="line"><span class="built_in">document</span>.body.onselectstart = <span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(e, <span class="string">'文字选择'</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="comment">// e.preventDefault();</span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">// 禁止复制</span></span><br><span class="line"><span class="built_in">document</span>.body.oncopy = <span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(e, <span class="string">'copy'</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="comment">// e.preventDefault();</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 禁止剪切</span></span><br><span class="line"><span class="built_in">document</span>.body.oncut = <span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(e, <span class="string">'cut'</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="comment">// e.preventDefault();</span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">// 禁止粘贴</span></span><br><span class="line"><span class="built_in">document</span>.body.onpaste = <span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(e, <span class="string">'paste'</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="comment">// e.preventDefault();</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<figure class="highlight css"><table><tr><td class="code"><pre><span class="line"><span class="comment">/** css 禁止文本选择 这样不会触发js**/</span></span><br><span class="line"><span class="selector-tag">body</span> &#123;</span><br><span class="line">    <span class="attribute">user-select</span>: none;</span><br><span class="line">    <span class="attribute">-moz-user-select</span>: none;</span><br><span class="line">    <span class="attribute">-webkit-user-select</span>: none;</span><br><span class="line">    <span class="attribute">-ms-user-select</span>: none;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>使用<code>e.preventDefault()</code>也可以禁用，但建议使用<code>return false</code>这样就不用去访问<code>e</code>和<code>e</code>的方法了。</li>
<li>示例中<code>document.body</code>全局都禁用了，也可以对 <code>dom</code>(某些区域)进行禁用</li>
</ul>
<p><strong>破解防复制</strong></p>
<p>上面的防复制方法通过<code>js+css</code>实现的，所以思路就是：禁用<code>js+取消user-select</code>样式。</p>
<blockquote>
<p><code>Chrome</code>浏览器的话：打开浏览器控制台，按<code>F1</code>进入<code>Setting</code>，勾选<code>Disable</code> <code>JavaScript</code>(禁止 <code>js</code>)。</p>
</blockquote>
<p><img src="https://upload-images.jianshu.io/upload_images/1480597-2f3188629fa5a86d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"></p>
<blockquote>
<p>此时如果还不能复制的话，就要去找<code>user-select</code>样式,取消这个样式就可以了</p>
</blockquote>
<h3 id="2-3-点击复制功能"><a href="#2-3-点击复制功能" class="headerlink" title="2.3 点击复制功能"></a>2.3 点击复制功能</h3><p><strong>不能使用 clipboardData</strong></p>
<ul>
<li>在 <code>IE</code> 中可以用<code>window.clipboardData.setData(&#39;text&#39;,&#39;内容&#39;)</code>实现</li>
<li>上文提到过，在 <code>IE</code> 中<code>clipboardData</code>是<code>window</code>的属性</li>
<li>而其他浏览器则是相应的<code>event</code>对象的属性，这实际上是一种安全措施，防止未经授权的访问,为了兼容其他浏览器，所以我们不能通过<code>clipboardData</code>来实现这种操作</li>
</ul>
<p><strong>具体做法</strong></p>
<ul>
<li>创建一个隐藏的<code>input</code>框</li>
<li>点击的时候，将要复制的内容放进<code>input</code>框中</li>
<li>选择文本内容<code>input.select()</code>。这里只能用<code>input</code>或者<code>textarea</code>才能选择文本</li>
<li><code>document.execCommand(&quot;copy&quot;)</code>，执行浏览器的复制命令</li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">copyText</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> text = <span class="built_in">document</span>.getElementById(<span class="string">'text'</span>).innerText; <span class="comment">// 获取要复制的内容也可以传进来</span></span><br><span class="line">  <span class="keyword">var</span> input = <span class="built_in">document</span>.getElementById(<span class="string">'input'</span>); <span class="comment">// 获取隐藏input的dom</span></span><br><span class="line">  input.value = text; <span class="comment">// 修改文本框的内容</span></span><br><span class="line">  input.select(); <span class="comment">// 选中文本</span></span><br><span class="line">  <span class="built_in">document</span>.execCommand(<span class="string">'copy'</span>); <span class="comment">// 执行浏览器复制命令</span></span><br><span class="line">  alert(<span class="string">'复制成功'</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-4-第三方库clipboard"><a href="#2-4-第三方库clipboard" class="headerlink" title="2.4 第三方库clipboard"></a>2.4 第三方库clipboard</h3><blockquote>
<p><a href="https://github.com/zenorocha/clipboard.js" target="_blank" rel="noopener">https://github.com/zenorocha/clipboard.js</a></p>
</blockquote>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2018/12/22/js-prototype-review/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2018/12/23/Object.defineProperty/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
